<template>
    <div class="stat-board">

        <!-- 筛选卡片 -->
        <el-card class="filter-card" shadow="never">
            <div class="card-header">

            </div>
            <el-form :inline="true" size="small" @submit.native.prevent="handleQuery">
                <el-form-item label="包名">
                    <el-select v-model="query.pk" placeholder="全部包名" @change="onPkChange" :loading="selectLoading">
                        <el-option v-for="pk in pkList" :key="pk.value" :label="pk.label" :value="pk.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="产品ID">
                    <el-select v-model="query.product_id" placeholder="全部产品" filterable @change="handleQuery"
                        :loading="selectLoading">
                        <el-option label="全部产品" value=""></el-option>
                        <el-option v-for="item in productList" :key="item" :label="item" :value="item"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="开始日期">
                    <el-date-picker v-model="query.start_date" type="date" value-format="yyyy-MM-dd"
                        :clearable="false" />
                </el-form-item>
                <el-form-item label="结束日期">
                    <el-date-picker v-model="query.end_date" type="date" value-format="yyyy-MM-dd" :clearable="false" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery" :loading="loading">
                        <i class="el-icon-search"></i> 查询
                    </el-button>
                    <el-button @click="resetFilter" :disabled="loading">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 统计卡片 -->
        <div class="stat-cards">
            <el-row :gutter="20">
                <el-col v-for="(card, idx) in statCards" :key="idx" :md="4" :sm="6" :xs="12">
                    <div class="stat-card" v-loading="loading">
                        <div class="card-icon">
                            <i :class="card.icon" :style="{ color: card.color }"></i>
                        </div>
                        <div class="card-content">
                            <div class="stat-number" :style="{ color: card.color }">
                                {{ loading ? '--' : card.value }}
                            </div>
                            <div class="card-title">{{ card.title }}</div>
                        </div>
                        <div class="card-bg-pattern"></div>
                    </div>
                </el-col>
            </el-row>
        </div>

        <!-- 图表区域 -->
        <el-row :gutter="20" class="chart-section">
            <el-col :span="24">
                <el-card class="chart-card" shadow="never">
                    <div class="chart-header">
                        <div class="chart-title">
                            <i class="el-icon-data-line"></i>
                            数据趋势图
                        </div>
                        <!-- <div class="chart-actions">
                            <el-button size="mini" type="text" @click="exportData">
                                <i class="el-icon-download"></i> 导出
                            </el-button>
                        </div> -->
                    </div>
                    <div class="chart-container" v-loading="loading">
                        <div class="police-count1" ref="chart1" style="height:400px;width:100%"></div>
                    </div>
                </el-card>
            </el-col>
            <!-- <el-col :span="8">
                <el-card class="task-card" shadow="never">
                    <div class="chart-header">
                        <div class="chart-title">
                            <i class="el-icon-setting"></i>
                            任务管理
                        </div>
                    </div>
                    <div class="task-actions">
                        <el-button type="success" size="small" @click="openTaskDialog('stat')" class="task-btn">
                            <i class="el-icon-video-play"></i> 手动执行统计
                        </el-button>
                        <el-button type="warning" size="small" @click="openTaskDialog('his')" class="task-btn">
                            <i class="el-icon-date"></i> 历史数据统计
                        </el-button>
                        <el-button type="info" size="small" @click="getJobStatus" class="task-btn"
                            :loading="statusLoading">
                            <i class="el-icon-info"></i> 查看任务状态
                        </el-button>
                    </div>
                    <el-divider />
                    <div class="status-info" v-if="jobStatus.isRunning !== undefined">
                        <div class="status-item">
                            <span class="status-label">状态：</span>
                            <el-tag :type="jobStatus.isRunning ? 'warning' : 'success'" size="small">
                                {{ jobStatus.isRunning ? '任务执行中' : '空闲' }}
                            </el-tag>
                        </div>
                        <div class="status-item">
                            <span class="status-label">上次：</span>
                            <span class="status-value">{{ jobStatus.lastExecuteTime }}</span>
                        </div>
                        <div class="status-item">
                            <span class="status-label">下次：</span>
                            <span class="status-value">{{ jobStatus.nextExecuteTime }}</span>
                        </div>
                    </div>
                </el-card>
            </el-col> -->
        </el-row>

        <!-- 任务对话框 -->
        <!-- <el-dialog :title="taskDialog.type === 'stat' ? '执行统计任务' : '历史数据统计'" :visible.sync="taskDialog.visible"
            width="450px" class="task-dialog">
            <el-form v-if="taskDialog.type === 'stat'" label-width="80px">
                <el-form-item label="包名" required>
                    <el-select v-model="taskDialog.pk" placeholder="请选择包名" style="width: 100%">
                        <el-option v-for="pk in pkList" :key="pk.value" :label="pk.label" :value="pk.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="日期">
                    <el-date-picker v-model="taskDialog.date" type="date" value-format="yyyy-MM-dd"
                        placeholder="不选默认为昨天" style="width: 100%" />
                </el-form-item>
            </el-form>
            <el-form v-else label-width="80px">
                <el-form-item label="包名" required>
                    <el-select v-model="taskDialog.pk" placeholder="请选择包名" style="width: 100%">
                        <el-option v-for="pk in pkList" :key="pk.value" :label="pk.label" :value="pk.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="开始日期" required>
                    <el-date-picker v-model="taskDialog.start_date" type="date" value-format="yyyy-MM-dd"
                        style="width: 100%" />
                </el-form-item>
                <el-form-item label="结束日期" required>
                    <el-date-picker v-model="taskDialog.end_date" type="date" value-format="yyyy-MM-dd"
                        style="width: 100%" />
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="taskDialog.visible = false">取消</el-button>
                <el-button type="primary" @click="confirmTask" :loading="taskLoading">确定</el-button>
            </span>
        </el-dialog> -->
    </div>
</template>

<script>
import {
    statisticStats,
    statisticProducts,
    statisticOverview,
    statisticExecuteStats,
    statisticExecuteHistorical,
    statisticJobStatus,
} from "@/api/statistic";
import axios from 'axios'

const pkLabelMap = {
    "com.finger.AINoteTaker": "AiNote",
    "com.seamobitech.BeautyAI": "Beauty",
    "com.seamobitech.HeartPulse": "HeartPulse",
    "com.seamobitech.QRCodeReadAndGenerate": "QRCode",
    "com.seamobitech.roku": "roku",
    "com.seamobitech.UniversalTVRemoteControl": "universalControl",
    "com.seamobitech.whatsscanwebclone": "WA",
    "com.trans.translationAiAndSubtitle": "Transir",
    "com.zhijian.remoteControl": "universalRemote2"
};

export default {
    data() {
        return {
            query: {
                pk: '',
                product_id: '',
                start_date: '',
                end_date: '',
            },
            productList: [],
            pkList: [],
            statCards: [
                { title: '总续订数', value: 0, icon: 'el-icon-refresh', color: '#1976d2' },          // 蓝
                { title: '总退款数', value: 0, icon: 'el-icon-refresh-left', color: '#e53935' },    // 红
                { title: '总试用数', value: 0, icon: 'el-icon-time', color: '#43a047' },            // 绿
                { title: '一次性购买数', value: 0, icon: 'el-icon-bank-card', color: '#8e24aa' },   // 紫
                { title: '无试用购买数', value: 0, icon: 'el-icon-shopping-cart-full', color: '#fbc02d' }, // 金黄
                { title: '转正数', value: 0, icon: 'el-icon-success', color: '#f4511e' },           // 橙
                { title: '平均转正率', value: '0%', icon: 'el-icon-s-data', color: '#ffea00' },     // 亮黄
                { title: '恢复订阅', value: 0, icon: 'el-icon-refresh-right', color: '#00bcd4' },   // 青/蓝
            ],

            loading: false,
            selectLoading: false,
            statusLoading: false,
            taskLoading: false,
            trendData: [],
            jobStatus: {},
            taskDialog: {
                visible: false,
                type: 'stat',
                pk: '',
                date: '',
                start_date: '',
                end_date: ''
            }
        }
    },
    mounted() {
        this.initQuery();
        this.fetchProductList();
    },

    methods: {
        initQuery() {
            const today = new Date();
            const lastWeek = new Date(today - 15 * 24 * 60 * 60 * 1000);
            this.query.start_date = lastWeek.toISOString().slice(0, 10);
            this.query.end_date = today.toISOString().slice(0, 10);
        },

        async fetchProductList() {
            this.selectLoading = true;
            try {
                const res = await statisticProducts();
                if (res.success && Array.isArray(res.data)) {
                    const allPks = [...new Set(res.data.map(r => r.pk))];
                    this.pkList = allPks.map(pk => ({
                        value: pk,
                        label: pkLabelMap[pk] || pk
                    }));
                    if (!this.query.pk && this.pkList.length > 0) {
                        this.query.pk = this.pkList[0].value;
                        this.fetchProductListByPk();
                        this.fetchAll();
                    }
                }
            } catch (e) {
                this.$message.error('加载产品失败');
            } finally {
                this.selectLoading = false;
            }
        },

        async fetchProductListByPk() {
            this.selectLoading = true;
            try {
                const res = await statisticProducts();
                if (res.success && Array.isArray(res.data)) {
                    this.productList = [...new Set(res.data.filter(r => r.pk === this.query.pk).map(r => r.product_id))];
                    this.query.product_id = '';
                }
            } catch (e) {
                this.productList = [];
            } finally {
                this.selectLoading = false;
            }
        },

        async fetchAll() {
            this.loading = true;
            try {
                const params = { ...this.query };
                let res;
                if (params.pk == 'com.trans.translationAiAndSubtitle') {
                    let data = await axios.post('https://xiaoshuchengzhang.com/node/statistic/statisticOverviewMOMO', params);
                    res = data.data

                } else {
                    res = await statisticOverview(params);
                }
                if (res && res.success) {
                    const s = res.data.summary || {};
                    this.statCards[0].value = s.total_renewals || 0;
                    this.statCards[1].value = s.total_refunds || 0;
                    this.statCards[2].value = s.total_trial_users || 0;
                    this.statCards[3].value = s.total_one_time_purchase || 0;
                    this.statCards[4].value = s.total_direct_purchase || 0;
                    this.statCards[5].value = s.total_conversions || 0;
                    this.statCards[6].value = ((s.avg_conversion_rate || 0) * 100).toFixed(2) + '%';
                    this.statCards[7].value = s.total_resubscribe || 0;

                    this.trendData = res.data.trend || [];
                    this.drawChart();
                }
            } catch (e) {
                this.$message.error('加载数据失败');
            } finally {
                this.loading = false;
            }
        },

        handleQuery() {
            this.fetchAll();
        },

        async resetFilter() {
            this.query = { pk: '', product_id: '', start_date: '', end_date: '' };
            this.initQuery();
            await this.fetchProductList();
        },

        async onPkChange(val) {
            this.query.product_id = '';
            await this.fetchProductListByPk();
            this.fetchAll();
        },

        drawChart() {
            if (!this.$refs.chart1 || !this.trendData.length) return;
            if (!this.chart1) {
                this.chart1 = this.$echarts.init(this.$refs.chart1);
            }
            this.chart1.clear();

            this.chart1.setOption({
                backgroundColor: 'transparent',
                grid: {
                    left: '1%',
                    right: '1%',
                    bottom: '3%',
                    top: '8%',
                    containLabel: true
                },
                tooltip: {
                    trigger: 'axis',
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    borderColor: '#409EFF',
                    textStyle: { color: '#fff' }
                },
                legend: {
                    data: ['续订数', '试用数', '转正数', '退款数', '一次性购买','无试用购买', '转正率', '恢复订阅'],
                    textStyle: { color: '#606266' }
                },
                xAxis: {
                    type: 'category',
                    data: this.trendData.map(d => d.stat_date),
                    axisLine: { lineStyle: { color: '#e4e7ed' } },
                    axisTick: { lineStyle: { color: '#e4e7ed' } },
                    axisLabel: { color: '#606266' }
                },
                yAxis: [
                    {
                        type: 'value',
                        name: '人数',
                        nameTextStyle: { color: '#606266' },
                        axisLine: { lineStyle: { color: '#e4e7ed' } },
                        axisTick: { lineStyle: { color: '#e4e7ed' } },
                        axisLabel: { color: '#606266' },
                        splitLine: { lineStyle: { color: '#f5f7fa' } }
                    },
                    {
                        type: 'value',
                        name: '转正率(%)',
                        min: 0,
                        max: 100,
                        position: 'right',
                        nameTextStyle: { color: '#606266' },
                        axisLine: { lineStyle: { color: '#e4e7ed' } },
                        axisTick: { lineStyle: { color: '#e4e7ed' } },
                        axisLabel: {
                            formatter: '{value}%',
                            color: '#606266'
                        }
                    }
                ],
                series: [
                    {
                        name: '续订数', type: 'line',
                        data: this.trendData.map(d => d.daily_renewals || 0),
                        smooth: true, symbol: 'circle',
                        lineStyle: { color: '#1976d2', width: 3 },   // 蓝
                        itemStyle: { color: '#1976d2' },
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0, y: 0, x2: 0, y2: 1,
                                colorStops: [
                                    { offset: 0, color: 'rgba(25, 118, 210, 0.3)' },
                                    { offset: 1, color: 'rgba(25, 118, 210, 0.1)' }
                                ]
                            }
                        }
                    },
                    {
                        name: '退款数', type: 'line',
                        data: this.trendData.map(d => d.daily_refunds || 0),
                        smooth: true, symbol: 'diamond',
                        lineStyle: { color: '#e53935', width: 3 },   // 红
                        itemStyle: { color: '#e53935' }
                    },
                    {
                        name: '试用数', type: 'line',
                        data: this.trendData.map(d => d.daily_trial_users || 0),
                        smooth: true, symbol: 'triangle',
                        lineStyle: { color: '#43a047', width: 3 },   // 绿
                        itemStyle: { color: '#43a047' }
                    },
                    {
                        name: '一次性购买', type: 'line',
                        data: this.trendData.map(d => d.daily_one_time_purchase || 0),
                        smooth: true, symbol: 'rect',
                        lineStyle: { color: '#8e24aa', width: 3 },   // 紫
                        itemStyle: { color: '#8e24aa' }
                    },
                    {
                        name: '无试用购买', type: 'line',
                        data: this.trendData.map(d => d.daily_direct_purchase || 0),
                        smooth: true, symbol: 'rect',
                        lineStyle: { color: '#fbc02d', width: 3 },   // 金黄（深黄）
                        itemStyle: { color: '#fbc02d' }
                    },
                    {
                        name: '转正数', type: 'line',
                        data: this.trendData.map(d => d.daily_conversions || 0),
                        smooth: true, symbol: 'rect',
                        lineStyle: { color: '#f4511e', width: 3 },   // 橙
                        itemStyle: { color: '#f4511e' }
                    },
                    {
                        name: '转正率',
                        type: 'line',
                        yAxisIndex: 1,
                        data: this.trendData.map(d => ((d.daily_conversion_rate || 0) * 100).toFixed(2)),
                        smooth: true,
                        symbol: 'star',
                        lineStyle: { color: '#ffea00', width: 3 },    // 亮黄
                        itemStyle: { color: '#ffea00' }
                    },
                    {
                        name: '恢复订阅', type: 'line',
                        data: this.trendData.map(d => d.daily_resubscribe || 0),
                        smooth: true, symbol: 'circle',
                        lineStyle: { color: '#00bcd4', width: 3 },   // 青色
                        itemStyle: { color: '#00bcd4' }
                    }
                ]

            });
        },

        exportData() {
            this.$message.info('TODO: 可用xls等工具导出前端tableData');
        },

        openTaskDialog(type) {
            this.taskDialog.visible = true;
            this.taskDialog.type = type;
            this.taskDialog.pk = '';
            this.taskDialog.date = '';
            this.taskDialog.start_date = '';
            this.taskDialog.end_date = '';
        },

        async confirmTask() {
            if (!this.taskDialog.pk) return this.$message.warning('请选择包名');

            this.taskLoading = true;
            try {
                if (this.taskDialog.type === 'stat') {
                    const params = { pk: this.taskDialog.pk, date: this.taskDialog.date };
                    await statisticExecuteStats(params);
                    this.$message.success('统计任务提交成功');
                } else {
                    if (!this.taskDialog.start_date || !this.taskDialog.end_date) {
                        return this.$message.warning('请选择时间');
                    }
                    const params = {
                        pk: this.taskDialog.pk,
                        start_date: this.taskDialog.start_date,
                        end_date: this.taskDialog.end_date
                    };
                    await statisticExecuteHistorical(params);
                    this.$message.success('历史任务已触发');
                }
                this.taskDialog.visible = false;
            } catch (e) {
                this.$message.error('任务执行失败');
            } finally {
                this.taskLoading = false;
            }
        },

        async getJobStatus() {
            this.statusLoading = true;
            try {
                const res = await statisticJobStatus();
                if (res && res.success) {
                    this.jobStatus = res.data;
                    this.$message.success('已刷新任务状态');
                }
            } catch (e) {
                this.$message.error('获取任务状态失败');
            } finally {
                this.statusLoading = false;
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.stat-board {
    padding: 20px;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    min-height: 100vh;
}

// 头部样式
.page-header {
    margin-bottom: 24px;
    position: relative;

    .page-title {
        color: #2c3e50;
        font-size: 28px;
        font-weight: 600;
        margin: 0;
        display: flex;
        align-items: center;

        i {
            margin-right: 12px;
            color: #409EFF;
        }
    }

    .header-decoration {
        height: 4px;
        background: linear-gradient(90deg, #409EFF, #67c23a);
        border-radius: 2px;
        margin-top: 8px;
        width: 100px;
    }
}

// 筛选卡片
.filter-card {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 12px;
    margin-bottom: 24px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);

    .card-header {
        display: flex;
        align-items: center;
        margin-bottom: 16px;
        font-size: 16px;
        font-weight: 600;
        color: #2c3e50;

        i {
            margin-right: 8px;
            color: #409EFF;
        }
    }
}

// 统计卡片
.stat-cards {
    margin: 24px 0;
}

.stat-card {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 16px;
    padding: 24px;
    margin-bottom: 20px;
    position: relative;
    overflow: hidden;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    cursor: pointer;

    &:hover {
        transform: translateY(-4px);
        box-shadow: 0 12px 48px rgba(0, 0, 0, 0.15);
    }

    .card-icon {
        position: absolute;
        top: 20px;
        right: 20px;
        font-size: 32px;
        opacity: 0.8;
    }

    .card-content {
        position: relative;
        z-index: 2;
    }

    .stat-number {
        font-size: 32px;
        font-weight: 700;
        margin-bottom: 8px;
        line-height: 1;
    }

    .card-title {
        font-size: 14px;
        color: #606266;
        font-weight: 500;
    }

    .card-bg-pattern {
        position: absolute;
        top: 0;
        right: 0;
        width: 100px;
        height: 100px;
        background: linear-gradient(45deg, rgba(64, 158, 255, 0.1), rgba(103, 194, 58, 0.1));
        border-radius: 50%;
        transform: translate(30px, -30px);
    }
}

// 图表区域
.chart-section {
    margin-top: 24px;
}

.chart-card,
.task-card {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .chart-title {
        font-size: 18px;
        font-weight: 600;
        color: #2c3e50;
        display: flex;
        align-items: center;

        i {
            margin-right: 8px;
            color: #409EFF;
        }
    }
}

.chart-container {
    border-radius: 8px;
    overflow: hidden;
}

// 任务管理
.task-actions {
    display: flex;
    flex-direction: column;
    gap: 12px;

    .task-btn {
        width: 100%;
        border-radius: 8px;
        border: none;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;

        &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
        }
    }
}

.status-info {
    background: rgba(64, 158, 255, 0.05);
    border-radius: 8px;
    padding: 16px;
    border: 1px solid rgba(64, 158, 255, 0.1);

    .status-item {
        display: flex;
        align-items: center;
        margin-bottom: 8px;

        &:last-child {
            margin-bottom: 0;
        }

        .status-label {
            font-weight: 600;
            color: #2c3e50;
            min-width: 50px;
        }

        .status-value {
            color: #606266;
            font-size: 14px;
        }
    }
}

// 对话框
.task-dialog {
    ::v-deep .el-dialog {
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(10px);
        border-radius: 16px;
        box-shadow: 0 16px 64px rgba(0, 0, 0, 0.2);
    }

    ::v-deep .el-dialog__header {
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    }

    ::v-deep .el-dialog__title {
        color: #2c3e50;
        font-weight: 600;
    }
}

// 响应式设计
@media (max-width: 768px) {
    .stat-board {
        padding: 16px;
    }

    .page-title {
        font-size: 24px;
    }

    .chart-section {
        .el-col {
            margin-bottom: 20px;
        }
    }

    .task-actions {
        .task-btn {
            font-size: 12px;
        }
    }
}

// 加载动画
@keyframes pulse {
    0% {
        opacity: 1;
    }

    50% {
        opacity: 0.5;
    }

    100% {
        opacity: 1;
    }
}

.loading-pulse {
    animation: pulse 1.5s ease-in-out infinite;
}
</style>